package com.myalibaba.util;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.Arrays;
import java.util.List;

/**
 * java -jar MySpringCloudAlibaba-0.0.1-SNAPSHOT.jar --spring.profiles.active=prod
 * 判断当前运行环境是测试环境还是生产环境
 */
@Component
public class EnvironmentUtil implements ApplicationContextAware {
    private static ApplicationContext context;
    //使用 volatile 关键字修饰 environment 变量：这样可以确保变量在不同线程间的可见性，避免了同步的开销。
    private static volatile  Environment environment;

    @Autowired
    private Environment autowiredEnvironment;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        context = applicationContext;
    }

    @PostConstruct
    public void init() {
        environment = this.autowiredEnvironment;
        System.out.println("Environment类初始化");
    }

    public static Environment getEnvironment() {
        if (environment == null) {
            synchronized (EnvironmentUtil.class) {
                if (environment == null) {
                    System.out.println("获取Environment类");
                    environment = context.getBean(Environment.class);
                }
            }
        } else {
            System.out.println("Environment类已经初始化");
        }
        return environment;
    }

    // 获取配置
    public static String getConfig(String key) {
        return getEnvironment().getProperty(key);
    }

    public static boolean isProdProfile() {
        return Arrays.asList(getEnvironment().getActiveProfiles()).contains("prod");
    }

    public static boolean isDevProfile() {
        List<String> profiles = Arrays.asList(getEnvironment().getActiveProfiles());
        return profiles.contains("dev") || profiles.isEmpty();
    }

    public static String getActiveProfile() {
        String activeProfile = System.getenv("SPRING_PROFILES_ACTIVE");
        if (activeProfile == null || activeProfile.isEmpty()) {
            activeProfile = Arrays.asList(getEnvironment().getActiveProfiles()).stream()
                    .findFirst()
                    .orElse("");
        }
        return activeProfile;
    }
}
